/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import 'react-native-gesture-handler';

import {
  BackHandler,
  LogBox,
  Platform,
  SafeAreaView,
  ToastAndroid,
} from 'react-native';
import {Provider} from 'react-redux';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import {RootSiblingParent} from 'react-native-root-siblings';
import React, {Component} from 'react';
import {RootStore, RootNavigator} from './store/root-store';
import {ActionSheetProvider} from '@expo/react-native-action-sheet';
import {NavigationActions} from 'react-navigation';
import {isTopRoute} from './utils';
import {I18n} from './reducers/intl';
import 'react-native-gesture-handler';

class App extends Component {
  constructor() {
    super();
    LogBox.ignoreLogs([
      'Warning: isMounted(...) is deprecated',
      'componentWillReceiveProps has been renamed',
      'componentWillMount has been renamed',
      'Module RCTImageLoader',
      'Remote debugger is in a background tab',
      '"null" is not a valid color or brush',
    ]);
  }

  componentWillMount() {
    if (Platform.OS === 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  componentWillUnmount() {
    if (Platform.OS === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  onBackAndroid = () => {
    const {nav} = RootStore.getState();
    const isTop = isTopRoute(nav);
    // console.log(isTop, JSON.stringify(nav));
    if (isTop) {
      if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
        BackHandler.exitApp(); //直接退出APP
      } else {
        this.lastBackPressed = Date.now();
        ToastAndroid.show(I18n.t('toast.quit'), 1000); //提示
        return true;
      }
    } else {
      RootStore.dispatch(NavigationActions.back());
      return true;
    }
  };

  render() {
    return (
      <SafeAreaProvider>
        <Provider store={RootStore}>
          <ActionSheetProvider>
            <SafeAreaView style={{flex: 1}}>
              <RootSiblingParent>
                <RootNavigator />
              </RootSiblingParent>
            </SafeAreaView>
          </ActionSheetProvider>
        </Provider>
      </SafeAreaProvider>
    );
  }
}

export default App;
